import LogicConfigTs from "./LogicConfigTs";
import GameDataUtilTs from "./GameDataUtilTs";
import LanguageMng from "../Managers/LanguageMng";

cc.Class({
    extends: cc.Component,

    ctor(){
        this.backTimes = 0
        cc.game.onBackPressed = function () {
            this._onBackPressed()
        }.bind(this)

        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown.bind(this), this)
    },

    _onBackPressed(){
        let sceneName = GameDataUtilTs.getCurrentSceneName()
        if(sceneName === LogicConfigTs.SCENENAME_LOBBY){
            cc.gg.baseUtil._askQuitGame()
        }else if(sceneName === LogicConfigTs.SCENENAME_GAME_2 || sceneName === LogicConfigTs.SCENENAME_GAME_6){
            cc.gg.baseUtil.backTimes++
            if(cc.gg.baseUtil.backTimes === 2)
                cc.game.end()

            cc.gg.toastMgr.showToast("Press again to quit game")
            cc.gg.baseUtil.scheduleOnce(function () {
                this.backTimes = 0
            }.bind(cc.gg.baseUtil), 1)
        }else {
            cc.gg.baseUtil.backTimes++
            if(cc.gg.baseUtil.backTimes === 2)
                cc.game.end()

            cc.gg.toastMgr.showToast("Press again to quit game")
            cc.gg.baseUtil.scheduleOnce(function () {
                this.backTimes = 0
            }.bind(cc.gg.baseUtil), 1)
        }
    },

    _askQuitGame(){
        let title = LanguageMng.getSentence(200)  //Confirm
        let positiveStr = LanguageMng.getSentence(57)   //Yes
        let passiveStr = LanguageMng.getSentence(179)   //Cancel
        let content = LanguageMng.getSentence(236)  //Are you sure to quit game?
        cc.gg.toastMgr.showDialog(title,positiveStr,passiveStr,content,
            function () {
                cc.game.end()
            },
            function () {
                cc.gg.toastMgr.removeDialog()
            }
        )
    },

    onKeyDown(event) {
        switch (event.keyCode) {
            //注意Creator版本为2.x的请把cc.KEY.back。修改成cc.macro.KEY.back
            case cc.macro.KEY.back:
                cc.game.onBackPressed()
                break;
        }
    },

    onBackPressed:function () {
        this.backTimes++
        if(this.backTimes === 2)
            cc.game.end()

        cc.gg.toastMgr.showToast("Press again to quit game")
        this.scheduleOnce(function () {
            this.backTimes = 0
        }.bind(this), 1)
    },

    isArrayValid(array){
        return array && array.length !== 0
    },

    addClickEventToNode:function (node,targetNode,handlerName,functionName) {
        var clickEventHandler = new cc.Component.EventHandler();
        clickEventHandler.target = targetNode; //这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = handlerName;//这个是代码文件名
        clickEventHandler.handler = functionName;
        clickEventHandler.customEventData = "foobar";

        var button = node.getComponent(cc.Button);
        button.clickEvents.push(clickEventHandler);
    },


    moveArrayElement:function(arr,index,tindex){
        //如果当前元素在拖动目标位置的下方，先将当前元素从数组拿出，数组长度-1，我们直接给数组拖动目标位置的地方新增一个和当前元素值一样的元素，
        //我们再把数组之前的那个拖动的元素删除掉，所以要len+1
        if(index>tindex){
            arr.splice(tindex,0,arr[index]);
            arr.splice(index+1,1)
        }
        else{
            //如果当前元素在拖动目标位置的上方，先将当前元素从数组拿出，数组长度-1，我们直接给数组拖动目标位置+1的地方新增一个和当前元素值一样的元素，
            //这时，数组len不变，我们再把数组之前的那个拖动的元素删除掉，下标还是index
            arr.splice(tindex+1,0,arr[index]);
            arr.splice(index,1)
        }
    },

    getWorldPos:function (node) {
        return node.parent.convertToWorldSpaceAR(node.position)
    },

    getMapLength:function (map) {
        let length = 0
        for(let key in map){
            if(map[key].name)
                length++
        }
        return length
    },
    
    arrayRemove:function (array, g1) {
        var index = array.indexOf(g1);
        if (index > -1) {
            array.splice(index, 1);
            return true
        }
        return false
    },

    arrayAllEquall:function (array,value) {
        if (array.length > 1) {
            return !array.some(function (value, index) {
                return value !== array[0]
            }.bind(array));
        } else {
            return true;
        }
    },

    setLandscape(num) {
        if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity",
                "setOrientation", "(I)V", num); //1横2竖
        }else if (cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod("IOSHelper", "setOrientation:", num);
        }else {

        }

        if(num === 1){
            cc.log("js设置为横屏")
            cc.view.setOrientation(cc.macro.ORIENTATION_LANDSCAPE);
            cc.view.setFrameSize(1440, 720);
            cc.view.setDesignResolutionSize(1440, 720, cc.ResolutionPolicy.FIXED_HEIGHT);
        }else if(num === 2){
            cc.log("js设置为竖屏")
            cc.view.setOrientation(cc.macro.ORIENTATION_PORTRAIT);
            cc.view.setFrameSize(720, 1440);
            cc.view.setDesignResolutionSize(720, 1440, cc.ResolutionPolicy.FIXED_HEIGHT);
        }
        // window.emit(new cc.Event.EventCustom('resize', true))
    },


    // setKeyboardMode(num) {
    //     cc.log("cocos想要调用setKeyboardMode！",num)
    //     if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
    //         cc.log("andorid...+")
    //         jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity",
    //             "setKeyboardMode", "(I)V", num); //1不做任何处理；2将页面顶上去
    //     }else if (cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS) {
    //         cc.log("ios...+")
    //         jsb.reflection.callStaticMethod("IOSHelper", "setKeyboardMode:", num);
    //     }else {
    //
    //         cc.log("unknwon platform...+")
    //     }
    // },

    openWhatsApp:function (groupLink) {
        if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
            var className = "org/cocos2dx/javascript/AppActivity";
            var methodName = "openWhatsApp";
            var methodSignature = "(Ljava/lang/String;)V";
            jsb.reflection.callStaticMethod(className, methodName, methodSignature, groupLink);
        }else if (cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS) {
            // jsb.reflection.callStaticMethod("IOSHelper", "setOrientation:", num);
        }else {

        }
    },

    vibrate:function (milliSeconds) {
        if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
            var className = "org/cocos2dx/javascript/AppActivity";
            var methodName = "vibrate";
            var methodSignature = "(I)V";
            jsb.reflection.callStaticMethod(className, methodName, methodSignature, milliSeconds);
        }else if (cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS) {
            // jsb.reflection.callStaticMethod("IOSHelper", "setOrientation:", num);
        }else {

        }
    },

    openGalary:function (uploadUrl,uploadType,token) {
        cc.gg.toastMgr.showNetWaitting(function () {
            if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
                var className = "org/cocos2dx/javascript/AppActivity";
                var methodName = "openGalary";
                var methodSignature = "(Ljava/lang/String;ILjava/lang/String;)V";
                jsb.reflection.callStaticMethod(className, methodName, methodSignature, uploadUrl,uploadType,token);
            }else if (cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS) {
                // jsb.reflection.callStaticMethod("IOSHelper", "setOrientation:", num);
            }else {
                cc.warn("什么平台都不是")
                setTimeout(function () {
                    cc.gg.toastMgr.removeNetWaitting()
                }.bind(this),1000)
            }
        })
    },

    isValidString:function (testString) {
        return testString && testString !== ""
    },

    isAllNumber:function (num) {
        return (/^[0-9]+$/.test(num))
    },

    delta_days:function(dt,t)
    {
        var d = new Date(t * 1000);
        d.setHours(0);
        d.setMinutes(0);
        d.setSeconds(0);
        var n = new Date(dt * 1000);
        n.setHours(0);
        n.setMinutes(0);
        n.setSeconds(0);
        console.log(t + " " + n.getTime() + " " + d.getTime());
        return Math.floor((n.getTime() - d.getTime()) / 24 / 3600 / 1000);
    },

    loginWithGoogle:function () {
        if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
            var className = "org/cocos2dx/javascript/AppActivity";
            var methodName = "signInGoogle";
            var methodSignature = "()V";
            jsb.reflection.callStaticMethod(className, methodName,methodSignature);
        }else if (cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS) {
            // jsb.reflection.callStaticMethod("IOSHelper", "setOrientation:", num);
        }else {

        }
    },

    loginWithFaceBook:function () {
        if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
            var className = "org/cocos2dx/javascript/AppActivity";
            var methodName = "signInFacebook";
            var methodSignature = "()V";
            jsb.reflection.callStaticMethod(className, methodName,methodSignature);
        }else if (cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS) {
            // jsb.reflection.callStaticMethod("IOSHelper", "setOrientation:", num);
        }else {

        }
    },

    getNewStringByReplace(oriStr,mainNameHolder,replaceStr){
        if(!oriStr)
            return "unknown"
        var regMain = new RegExp( mainNameHolder.toString() , "g" )
        let newStr = oriStr.replace(regMain,replaceStr)
        return newStr
    },
});
1